//Nick Object
function NickObject(friendID, nick, friendName, photoUrl,profileUrl, id){
	this.friendID = friendID;
	this.nick = nick;
	this.friendName = friendName;
	this.photoUrl = photoUrl;
	this.profileUrl = profileUrl;
	this.id = id;
	}

//NotAllowedNick Object	
function NotAllowedNick(id){
		this.id = id;
	}


var globalViewer = null;
var globalOwner = null;
var globalFriends = {};
var maxFriendsInPage = 20;
var columnCount = 5;
var currentPage = 0;
var tabs = null;
var Hi5AuthToken = null;
var friendsInPage;
var givenNicks = new Array();
var dataContainer = new Array();
var maxLatestNicks = 10;
var currView = null;
var notAllowedNicks = new Array();
var totalFriends = 0;
var recentItems = new Array();


function buildTabs(){
	tabs = new gadgets.TabSet('moduleID', null, document.getElementById('tabsPane'));
	tabs.alignTabs('left', 3);
	var params = {
  		callback: changeSelectedTab
	};
	var prefs = new _IG_Prefs();
	params.contentContainer = document.getElementById('receivedNicks');
	tabs.addTab(prefs.getMsg("receivedNicks"), params);
	params.contentContainer = document.getElementById('giveNicks');
	tabs.addTab(prefs.getMsg("giveNicks"), params);
	params.contentContainer = document.getElementById('nicksSent');
	tabs.addTab(prefs.getMsg("sentNicks"), params);
	
}


function init() {
  currView = gadgets.views.getCurrentView();
  buildTabs(); 
  loadFriends();
  loadReceivedNicks();  
}

function initForProfile(){
  currView = gadgets.views.getCurrentView();
  setupView();
  loadReceivedNicks();
}

function setupView(){	
	if(currView.getName() != 'profile' && currView.getName() != 'canvas'){
		maxFriendsInPage = 9;
		columnCount = 3;
		maxLatestNicks = 5;
	}
	if(currView.getName() == 'canvas'){
		maxFriendsInPage = 20;
		columnCount = 5;
		maxLatestNicks = 10;
	}
	if(currView.getName() == 'profile'){
		maxFriendsInPage = 3;
		columnCount = 3;
		maxLatestNicks = 2;
	}
}

function changeSelectedTab(){
	if (document.getElementById('tabs_header')) {
    	var tabHeaders = document.getElementById('tabs_header').rows[0].cells;
    	for (var i in tabHeaders) {
    		if (tabHeaders[i].className && tabHeaders[i].className.match(/tablib_selected/)) {
        		if (tabHeaders[i].childNodes[0].className) {
          			tabHeaders[i].childNodes[0].className = 'tablib_extension_left_selected';
        		}
      		}
      		if (tabHeaders[i].className !== undefined && tabHeaders[i].className.match(/tablib_unselected/)) {
        		if (tabHeaders[i].childNodes[0].className) {
         	 		tabHeaders[i].childNodes[0].className = 'tablib_extension_left_unselected';
        		}
      		}
    	}
 	}
}

function doNicks(){
	var textBoxes = document.getElementsByTagName('input');
	var sendNicks = false;
	recentItems = new Array();
	if(givenNicks == null)
		givenNicks = new Array()
	for(var i=0; i<= textBoxes.length ; i++){
		if(IsFriendTextBox(textBoxes[i]) == true){	
			if(textBoxes[i].value.length > 0){
				var item = new NickObject(textBoxes[i].id,textBoxes[i].value,
					friendsInPage[textBoxes[i].id].getDisplayName(),friendsInPage[textBoxes[i].id].getField(opensocial.Person.Field.THUMBNAIL_URL),friendsInPage[textBoxes[i].id].getField(opensocial.Person.Field.PROFILE_URL),new Date().getTime());
				givenNicks[givenNicks.length] = item;
				recentItems.push(item);
				sendNicks = true;
			}	
		}
	}
    if(sendNicks == true)
    {
    	var prefs = new _IG_Prefs();
    	var req = BuildRequestForUpdate(givenNicks);
    	req.send(onDoNicks);
		
    }	
    return false;
}

function onDoNicks(data){
	//Clear textboxes
	var textBoxes = document.getElementsByTagName('input');
	for(var i=0; i<= textBoxes.length ; i++){
		if(IsFriendTextBox(textBoxes[i]) == true){	
			if(textBoxes[i].value.length > 0){
				textBoxes[i].value = '';
			}	
		}
	}
	globalViewer = data.get('viewer').getData();
  	globalOwner = data.get('owner').getData();
	var nicksData = data.get('data').getData();
	var profileURL = globalOwner.getField(opensocial.Person.Field.PROFILE_URL);
	var sender = globalOwner.getDisplayName();
	sendNotifications(recentItems,profileURL,sender);
	postActivities(recentItems, profileURL, sender);	
	updateNicksList(nicksData);
	tabs.setSelectedTab(2);
}

function BuildRequestForUpdate(nicksToSave){
	var jsonStream = gadgets.json.stringify(nicksToSave);
    	var opts = {};
  		opts[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = 
                     [opensocial.Person.Field.AGE, 
	                  opensocial.Person.Field.NAME, 
	                  opensocial.Person.Field.GENDER, 
                      opensocial.Person.Field.PROFILE_URL, 
	                  opensocial.Person.Field.THUMBNAIL_URL,
                      opensocial.Person.Field.STATUS,
                      'presence'];
                      
		var req = opensocial.newDataRequest();
		
		req.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, 'nicks', jsonStream));		
		req.add(req.newFetchPersonRequest("VIEWER",opts), 'viewer');
		req.add(req.newFetchPersonRequest('OWNER', opts), 'owner', opts);
		req.add(req.newFetchPeopleRequest("VIEWER_FRIENDS",opts), 'viewerFriends');
		req.add(req.newFetchPersonAppDataRequest('VIEWER', 'nicks'), 'data');		
		return req;
}

function postActivities(recentGivenNicks,profileURL,sender){
	for(var givenNick in recentGivenNicks){
		postActivity(recentGivenNicks[givenNick], profileURL, sender);
	}
}

function sendNotifications(recentGivenNicks, profileURL, sender){
	for(var givenNick in recentGivenNicks){
		var to = new Array();
		to.push(recentGivenNicks[givenNick].friendID);
		var prefs = new _IG_Prefs();
		var notification = '<a href="' + profileURL +'">' + sender + ' ' + prefs.getMsg('gaveANick') + '. ' + '<a href="/friend/apps/displayAppCanvas.do?appId=7424&userid='+ recentGivenNicks[givenNick].friendID + '">' + prefs.getMsg('addApplication') + ' ' +  globalViewer.getDisplayName() + '!</a>' ;		
		sendNotification(notification,to);
	}
}

function postActivity(givenNick, profileURL, sender) {
  var prefs = new _IG_Prefs();
  var title = '<a href="' + profileURL +'">' + sender + '</a> ' + prefs.getMsg('gave') + ' <a href="'+ givenNick.profileUrl + '">'+ givenNick.friendName +'</a>' + ' ' + prefs.getMsg('theNick') + ' "' + givenNick.nick + '"';
  var params = {};
  params[opensocial.Activity.Field.TITLE] = title;
  var activity = opensocial.newActivity(params);
  opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, function() {});
}

function sendNotification(notification, toIds) { 
    var params = new Object(); 
    params[opensocial.Message.Field.TYPE] = opensocial.Message.Type.NOTIFICATION; 
    var message = opensocial.newMessage(notification, params);
    opensocial.requestSendMessage(toIds, message); 
}

function IsFriendTextBox(textBox){
	if(textBox != undefined && textBox["id"] != undefined){
		if(friendsInPage[textBox.id] != null || friendsInPage[textBox.id] != undefined)		
			return true;
	}
	return false;
}



function nextPage(){
	if(currentPage*maxFriendsInPage < totalFriends){
		currentPage = currentPage + 1;
		loadFriends();
	}
}

function previousPage(){
	if(currentPage > 0){
		currentPage = currentPage - 1;
		loadFriends();
	}
}

function loadFriends(){
  setupView();
  loadingStart();
  var opts = {};
  opts[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = 
                     [opensocial.Person.Field.AGE, 
	                  opensocial.Person.Field.NAME, 
	                  opensocial.Person.Field.GENDER, 
                      opensocial.Person.Field.PROFILE_URL, 
	                  opensocial.Person.Field.THUMBNAIL_URL,
                      opensocial.Person.Field.STATUS,
                      'presence'];
  opts[opensocial.DataRequest.PeopleRequestFields.FIRST] = maxFriendsInPage*currentPage;
  opts[opensocial.DataRequest.PeopleRequestFields.MAX] = maxFriendsInPage;  
  var req = opensocial.newDataRequest();
  req.add(req.newFetchPersonRequest('OWNER', opts), 'owner', opts);
  req.add(req.newFetchPersonRequest("VIEWER",opts), 'viewer');
  req.add(req.newFetchPeopleRequest("VIEWER_FRIENDS",opts), 'viewerFriends');
  req.add(req.newFetchPersonAppDataRequest('VIEWER', 'nicks'), 'data');  
  req.send(onLoadFriends);
}





function onLoadFriends(data){
  var colIndex = 0;
  friendsInPage = new Array();
  globalViewer = data.get('viewer').getData();
  globalOwner = data.get('owner').getData();
  var viewerFriends = data.get('viewerFriends').getData();
  totalFriends = viewerFriends.totalSize_;
  var nicksData = data.get('data').getData();
  var friends = new Array();
  html = new Array();
  html.push('<table>')
  html.push('<tr>')
  viewerFriends.each(function(person) {
    
    if(colIndex == columnCount){
        colIndex = 0;
        html.push('</tr>');
    	html.push('<tr>');
    }
    html.push('<td>')
    friends[person.getId()] = person.getDisplayName();
    friendsInPage[person.getId()] = person;
    html.push('<div class="friend" style="margin-top:5px;padding-top:5px"><div class="friendCard" valign="middle"><a href="' + person.getField(opensocial.Person.Field.PROFILE_URL) +'" target="_blank" >' + person.getDisplayName() +'</a></div><div class="friendPicture" >' + ' <img border="0" height="100px" width="100px" src="' + 
      person.getField('thumbnailUrl') + '"/></div>' + '<div><input class="nickInput" type="text" id="' + person.getId() +'" /></div></div>');
    html.push('</td>')
    colIndex++;
  });
  html.push('</tr>')
  html.push('</table>')
  globalFriends = friends;
  document.getElementById('friends').innerHTML = html.join('');
  updateNicksList(nicksData);
  loadingFinished();
}

function loadingStart(){
    if(document.getElementById('loadingInfo').childNodes.length <= 0){
		var prefs = new _IG_Prefs();
		var loading = document.createTextNode(prefs.getMsg('loading'));
		document.getElementById('loadingInfo').appendChild(loading);
	}	
}

function loadingFinished(){
	if(document.getElementById('loadingInfo').childNodes.length > 0){
		document.getElementById('loadingInfo').removeChild(document.getElementById('loadingInfo').childNodes[0]);
	}
}

function updateNicksList(data) {
  if(data == null || data == undefined || data[globalViewer.getId()] == undefined)
  	return;  	
  var prefs = new _IG_Prefs();
  var json = data[globalViewer.getId()]['nicks'];
  if (!json) {
    givenNicks = new Array();
  }
  try {
    givenNicks = gadgets.json.parse(gadgets.util.unescapeString(json));
  } catch (e) {
    givenNicks = new Array();
  }
  var html = new Array();
  html.push('<span class="subTitle">' + prefs.getMsg('haveGiven') + '</span>');
  html.push('<ul class="list">');
  var count = 0;
  var givenCount = 0;
  var startIndex = 0;
  if(givenNicks != undefined && givenNicks != null){
  	if(givenNicks.length > maxLatestNicks){
    	startIndex = maxLatestNicks - givenNicks.length;
  		startIndex = Math.abs(startIndex);
  	}
  	for (givenNick in givenNicks) {
  		  if(count >= startIndex){
      		if(givenCount < maxLatestNicks){
  	  			html.push('<li><div><div valign="middle"></div><div class="friendPicture" >' + ' <img style="height:40px;width:40px;" class="smallImageBox" src="' + 
      				givenNicks[givenNick].photoUrl + '"/><a href="'+ givenNicks[givenNick].profileUrl +'"><span class="sentNickText">' + givenNicks[givenNick].friendName + '</span></a></span> ' + prefs.getMsg('received') + ' "' + givenNicks[givenNick].nick + '"'  + '</span></div></div></li>');
      			givenCount++;
      		}		
      	}
      	count++;
  	}
  }	
  html.push('</ul>');
  document.getElementById('given').innerHTML = html.join('');
}

function deleteNick(nickID){
	var row = document.getElementById(nickID);
	row.parentNode.parentNode.removeChild(row.parentNode);
	if(notAllowedNicks == null || notAllowedNicks == undefined)
		notAllowedNicks = new Array();
	notAllowedNicks.push(new NotAllowedNick(nickID));
	var jsonStream = gadgets.json.stringify(notAllowedNicks);
    var opts = {};
  	opts[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = 
                     [opensocial.Person.Field.AGE, 
	                  opensocial.Person.Field.NAME, 
	                  opensocial.Person.Field.GENDER, 
                      opensocial.Person.Field.PROFILE_URL, 
	                  opensocial.Person.Field.THUMBNAIL_URL,
                      opensocial.Person.Field.STATUS,
                      'presence'];
    opts[opensocial.DataRequest.PeopleRequestFields.FIRST] = maxFriendsInPage*currentPage;
  	opts[opensocial.DataRequest.PeopleRequestFields.MAX] = maxFriendsInPage;              
                                            
	var req = opensocial.newDataRequest();		
	req.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, 'notAllowed', jsonStream));		
	req.add(req.newFetchPersonRequest('OWNER', opts), 'owner', opts);
    req.add(req.newFetchPersonRequest("VIEWER",opts), 'viewer');
    req.add(req.newFetchPeopleRequest("VIEWER_FRIENDS",opts), 'viewerFriends');
    req.add(req.newFetchPersonAppDataRequest('VIEWER', 'nicks'), 'data');
    req.add(req.newFetchPersonAppDataRequest('VIEWER_FRIENDS', 'nicks'), 'viewerFriendData');
    req.add(req.newFetchPersonAppDataRequest('VIEWER', 'notAllowed'), 'data2');		
	req.send(nicksDeleted);
}

function nicksDeleted(data){
	//Do something?
}

function loadReceivedNicks(){
	var opts = {};
	var page = 0;
   opts[opensocial.DataRequest.PeopleRequestFields.MAX] = 1000;
   opts[opensocial.DataRequest.PeopleRequestFields.FILTER] = opensocial.DataRequest.FilterType.HAS_APP;
   opts[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = 
        	             [opensocial.Person.Field.AGE, 
	        	          opensocial.Person.Field.NAME, 
	            	      opensocial.Person.Field.GENDER, 
                    	  opensocial.Person.Field.PROFILE_URL, 
	                  	  opensocial.Person.Field.THUMBNAIL_URL,
                      	  opensocial.Person.Field.STATUS,
                      	  'presence'];
  	var req = opensocial.newDataRequest();  
  	req.add(req.newFetchPersonRequest('OWNER', opts), 'owner', opts);
  	req.add(req.newFetchPersonRequest("VIEWER",opts), 'viewer');
  	req.add(req.newFetchPeopleRequest("VIEWER_FRIENDS",opts), 'viewerFriends');
  	req.add(req.newFetchPersonAppDataRequest('VIEWER', 'nicks'), 'data');
  	req.add(req.newFetchPersonAppDataRequest('VIEWER_FRIENDS', 'nicks'), 'viewerFriendData');
  	req.add(req.newFetchPersonAppDataRequest('VIEWER', 'notAllowed'), 'data2');
    req.send(onLoadReceivedNicks);
}


function onLoadReceivedNicks(data) {
	if(data == null || data == undefined)
  		return;
  	globalViewer = data.get('viewer').getData();
  	globalOwner = data.get('owner').getData();
    var viewerFriends = data.get('viewerFriends').getData();
    var nicksData = data.get('data').getData();
    notAllowedNicks = new Array();
    var viewerfriendData = data.get('viewerFriendData').getData();
    var friends = new Array();
  	var prefs = new _IG_Prefs();
  	viewerFriends.each(function(person) {
    	friends[person.getId()] = person.getDisplayName();
    });
    if(data.get('data2')){
    	var notAllowedData = data.get('data2').getData();
    	if(notAllowedData && notAllowedData[globalViewer.getId()] && notAllowedData[globalViewer.getId()]['notAllowed']){
  			var rawData = gadgets.util.unescapeString(notAllowedData[globalViewer.getId()]['notAllowed']);
  			if(!rawData){
  				notAllowedNicks = new Array();
  			}
  			try {
				notAllowedNicks = gadgets.json.parse(rawData);
			}
			catch (e){
				notAllowedNicks = {};
			}
		}	
	}
  	gadgets.util.unescapeString 
	var viewerId = globalOwner.getId();
	var html = new Array();
	var received = prefs.getMsg('youHaveReceived');
	html.push('<span class="subTitle">' + received + '</span><ul class="list">');
	viewerFriends.each(function(person) {
		var personData = viewerfriendData[person.getId()];
		if (personData) {
			var name = person.getDisplayName();
			var json = gadgets.util.unescapeString(viewerfriendData[person.getId()]['nicks']);
	    	var receivedNicks = {};
	    	if (!json) {
	    		receivedNicks = {};
			}
			try {
				receivedNicks = gadgets.json.parse(json);
			}
			catch (e){
				receivedNicks = {};
			}
			for (nick in receivedNicks) {
				if ( receivedNicks[nick].friendID == viewerId ) {
				    if(IsNickAllowed(notAllowedNicks,receivedNicks[nick].id)==true){
	    				html.push('<li style="padding-bottom:2px;padding-top:2px;width:350px; border-bottom: 1px solid #86A1C4;"><div valign="middle" id="' + receivedNicks[nick].id + '"><img alt="" class="smallImageBox" style="padding-left:3px;height:40px;width:40px;" src="'+ person.getField(opensocial.Person.Field.THUMBNAIL_URL) + '"/><span> "' + receivedNicks[nick].nick + '" ' + prefs.getMsg('from') + ' <a href="'+ person.getField(opensocial.Person.Field.PROFILE_URL) + '" target="_blank">' + person.getDisplayName() +  '</a></span><img align="right" valign="top" style="cursor:pointer; padding-bottom:2px" src="http://nicknameshi5.googlecode.com/svn/trunk/src/delete.gif" onclick="deleteNick(' + receivedNicks[nick].id  +');"></div></li>');
	    			}
	    		}
			}
	    }
	 });
	 html.push('</ul>');
	 if(currView.getName() == 'profile'){
	 	document.getElementById('receivedNicksProfile').innerHTML = html.join('');
	 }
	 else{
	 	document.getElementById('receivedNicks').innerHTML = html.join('');
	 }
}

function IsNickAllowed(notAllowedNicks, nickID)
{
	try{
		for(item in notAllowedNicks){
			if(notAllowedNicks[item].id == nickID)
				return false;
		}
	}	
	catch (e){
		return true;
	}
	return true;
		
}

function setSkin() {
	document.write('<style type="text/css">');
	document.write('select { font-size: 11px;}');
	document.write('.main {');
	bgColor = gadgets.skins.getProperty(gadgets.skins.Property.BG_COLOR);
	if(bgColor) {
	    document.write('background-color:'+bgColor+';');
	}
	bgImage = gadgets.skins.getProperty(gadgets.skins.Property.BG_IMAGE);
	if(bgImage) {
	    document.write('background-image: url('+bgImage+');');
	}	
	bgPosition = gadgets.skins.getProperty(gadgets.skins.Property.BG_POSITION);
	if(bgPosition) {
	    document.write('background-position:'+bgPosition+';');
	}
	bgRepeat = gadgets.skins.getProperty(gadgets.skins.Property.BG_REPEAT);
	if(bgRepeat) {
	    document.write('background-repeat:'+bgRepeat+';');
	}
	fontColor = gadgets.skins.getProperty(gadgets.skins.Property.FONT_COLOR);
	if(fontColor) {
	    document.write('color:'+fontColor+';');
	}
	document.write('}');
	anchorColor = gadgets.skins.getProperty(gadgets.skins.Property.ANCHOR_COLOR);
	if(anchorColor) {
		document.write('.main a, .main a:hover, .main a:visited { color:'+anchorColor+';}');
	}
	document.write('</style>');
}


function DeleteAll() {
	var req = opensocial.newDataRequest();
	req.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER,
        	'nicks',null),'data');
	req.send(onDeleteAll);
}

function getFriends(){
	gadgets.io.makeRequest('http://api.hi5.com/rest/feed/friends/'+globalOwner.getId(),
              function (response) {
                  return parseAtomDoc(response);
              }
              , {'METHOD' : 'GET', 'CONTENT_TYPE' : 'DOM'}
          );
}

function parseAtomDoc(response){
	var titles = new Array();
	var items = response.data.getElementsByTagName('title');
    for(var i = 0; i < items.length; i++) {
    	if(i > 0) {
        	var title = items.item(i).firstChild.nodeValue;
            titles[i-1] = title;
            return title;
        }
    }
	return '';
}
      
function onDeleteAll(){
	alert('deleted');
}